<template>
  <div id="set-field-data">
    <div class="bg-color-w">
      <p class="form-title">服务模块基本信息</p>
      <el-form v-model="Data" :label-position="'right'" label-width="160px">
        <el-row>
          <el-col :push="2" :span="10">
            <el-form-item label="服务环境编号:">
              <el-input v-model="Data.moduleCode" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :push="2" :span="10">
            <el-form-item label="服务模块名称:">
              <el-input v-model="Data.moduleName" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :push="2" :span="10">
            <el-form-item label="所属网关环境:">
              <el-input v-model="Data.gwEnvName" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bg-color-w mar-t-10">
      <p class="form-title">
        报文头定义-请求参数
        <span class="form-title-btn">
          <el-button type="primary" size="mini" @click="openPacketDialog('add','req')">新增</el-button>
        </span>
      </p>
      <el-table :data="packetData.reqPacketList">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="fieldCode" label="参数"></el-table-column>
        <el-table-column prop="fieldType" label="类型"></el-table-column>
        <el-table-column label="是否必输">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.fieldRequired" :disabled="true"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="fieldLength" label="长度"></el-table-column>
        <el-table-column prop="fieldName" label="中文名称"></el-table-column>
        <el-table-column prop="fieldDefVal" label="示例值"></el-table-column>
        <el-table-column prop="fieldEncoding" label="编码方式"></el-table-column>
        <el-table-column prop="fieldPattern" label="检查规则"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="openPacketDialog('edit','req',scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="removePacket(scope.row.fieldId, scope.row.linkId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="bg-color-w mar-t-10">
      <p class="form-title">
        报文头定义-响应参数
        <span class="form-title-btn">
          <el-button type="primary" size="mini" @click="openPacketDialog('add','res')">新增</el-button>
        </span>
      </p>
      <el-table :data="packetData.resPacketList">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="fieldCode" label="参数"></el-table-column>
        <el-table-column prop="fieldType" label="类型"></el-table-column>
        <el-table-column label="是否必输">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.fieldRequired" :disabled="true"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="fieldLength" label="长度"></el-table-column>
        <el-table-column prop="fieldName" label="中文名称"></el-table-column>
        <el-table-column prop="fieldDefVal" label="示例值"></el-table-column>
        <el-table-column prop="fieldEncoding" label="编码方式"></el-table-column>
        <el-table-column prop="fieldPattern" label="检查规则"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="openPacketDialog('edit','res',scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="removePacket(scope.row.fieldId, scope.row.linkId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="packetDialogTitle" :visible.sync="packetDialogVisible" @close="packetDialogClose" width="900px">
      <el-form :model="packetPostData" ref="packetPostForm" :rules="packetPostRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="参数" :label-width="formLabelWidth" prop="fieldCode">
              <el-input v-model="packetPostData.fieldCode" placeholder="请输入参数"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" :label-width="formLabelWidth" prop="fieldType">
              <el-select v-model="packetPostData.fieldType" placeholder="请选择类型" popper-class="zIndex-popper">
                <el-option
                  v-for="item in fieldTypeOpts"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否必输" :label-width="formLabelWidth" >
              <el-checkbox v-model="packetPostData.fieldRequired"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="长度" :label-width="formLabelWidth" prop="fieldLength">
              <el-input v-model="packetPostData.fieldLength" placeholder="请输入长度"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="中文名称" :label-width="formLabelWidth" prop="fieldName">
              <el-input v-model="packetPostData.fieldName" placeholder="请输入中文名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="示例值" :label-width="formLabelWidth" prop="fieldDefVal">
              <el-input v-model="packetPostData.fieldDefVal" placeholder="请输入示例值"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="编码方式" :label-width="formLabelWidth" >
              <el-input v-model="packetPostData.fieldEncoding" placeholder="请输入编码方式"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检查规则" :label-width="formLabelWidth" >
              <!-- <el-input v-model="packetPostData.fieldPattern" placeholder="请选择检查规则" :disabled="true"></el-input>
              <el-button type="text" @click="openRuleDialog">选择</el-button> -->
              <a href="javascript:void(0);" class="select" @click="openRuleDialog">
                <span>{{ packetPostData.fieldPattern && packetPostData.fieldPattern !== '' ? packetPostData.fieldPattern:'请选择检查规则' }}</span>
              </a>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="dialogbtn">
          <el-button @click="packetDialogReset()">重置</el-button>
          <el-button @click="packetDialogClose()">关闭</el-button>
          <el-button type="primary" @click="packetDialogSubmit()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- <el-dialog :title="ruleDialogTitle" :visible.sync="ruleDialogVisible">
      <el-table :data="ruleData.list">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column label="规则名称">
          <template slot-scope="scope">
            <el-button type="text" @click="selectRule(scope.row.rulePattern)">{{scope.row.ruleName}}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="规则编号" prop="ruleCode"></el-table-column>
        <el-table-column label="正则表达式" prop="rulePattern"></el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            {{new Date(scope.row.createTime*1000).getFullYear()+'/'+new Date(scope.row.createTime*1000).getMonth()+'/'+new Date(scope.row.createTime*1000).getDate()}}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="ruleData.total">
      </el-pagination>
    </el-dialog> -->
    <!-- 规则列表弹窗 -->
    <v-select
      :title="ruleDialogTitle"
      :isShow="ruleDialogVisible"
      :dataObj="ruleData"
      :tableLabels="tableLabels"
      @close="closeDialog"
      @page-changes="handlePageChanges"
      @select-data="selectRule"></v-select>
  </div>
</template>
<script type='text/ecmascript-6'>
  import VSelect from '../../../../comm/vSelect.vue'
  import ajax from '../../../../../api/ajax/ajax'
  import api from '../../../../../api/url'
  export default {
    name: 'set-err-msg',
    components: {
      VSelect
    },
    props: {
      Data: {},
      messages: {}
    },
    watch: {
      Data () {
        this.getPacketList()
      }
    },
    data () {
      return {
        // 分页数据
        currentPage: 1,
        pageSize: 10,
        ruleData: {},
        ruleDialogTitle: '规则列表',
        ruleDialogVisible: false,
        packetDialogTitle: '',
        packetDialogVisible: false,
        formLabelWidth: '140px',
        packetData: {},
        packetPostData: {},
        packetPostRules: {
          fieldCode: [
            {required: true, trigger: 'blur', message: '参数不能为空'}
          ],
          fieldType: [
            {required: true, trigger: 'change', message: '类型不能为空'}
          ],
          fieldLength: [
            {required: true, trigger: 'blur', message: '长度不能为空'},
            {pattern: /^[0-9]*$/, message: '长度必须为数字'}
          ],
          fieldName: [
            {required: true, trigger: 'blur', message: '中文名称不能为空'}
          ],
          fieldDefVal: [
            {required: true, trigger: 'blur', message: '示例值不能为空'}
          ]
        },
        packetPostDataCache: {},
        rowCache: {},
        iPacket: null,
        iType: '',
        fieldTypeOpts: [
          {value: 'string', label: 'string'},
          {value: 'int', label: 'int'},
          {value: 'long', label: 'long'},
          {value: 'double', label: 'double'},
          {value: 'decimal', label: 'decimal'},
          {value: 'date', label: 'date'},
          {value: 'time', label: 'time'},
          {value: 'datetime', label: 'datetime'},
          {value: 'list', label: 'list'}
        ],
        tableLabels: {
          ruleName: '规则名称',
          ruleCode: '规则编号',
          rulePattern: '正则表达式',
          createTime: '创建时间'
        }
      }
    },
    methods: {
      // 分页触发事件
      handleCurrentChange (e) {
        this.currentPage = e
        this.getRuleList(e, this.pageSize)
      },
      handleSizeChange (e) {
        this.currentPage = 1
        this.getRuleList(this.currentPage, e)
      },
      openRuleDialog () {
        this.ruleDialogVisible = true
      },
      selectRule (data) {
        this.packetPostData.fieldPattern = data.rulePattern
        this.ruleDialogVisible = false
      },
      openPacketDialog (e, type, row) {
        this.packetPostData = {}
        if (e === 'add') {
          this.iPacket = true
          this.packetDialogTitle = '新增报文定义'
        } else {
          this.rowCache = row
          this.iPacket = false
          this.packetDialogTitle = '修改报文定义'
          this.packetPostData = {
            childPacketList: [],
            directType: row.directType,
            fieldCode: row.fieldCode,
            fieldDefVal: row.fieldDefVal,
            fieldEncoding: row.fieldEncoding,
            fieldId: row.fieldId,
            fieldLength: row.fieldLength,
            fieldName: row.fieldName,
            fieldOrder: row.fieldOrder,
            fieldPattern: row.fieldPattern,
            fieldRequired: row.fieldRequired,
            fieldRuleId: row.fieldRuleId,
            fieldType: row.fieldType,
            linkId: row.linkId,
            linkType: row.linkType,
            parentId: row.parentId
          }
        }
        this.$nextTick(() => {
          this.$refs['packetPostForm'].clearValidate()
        })
        if (type === 'res') {
          this.packetDialogTitle += '-响应参数'
        } else {
          this.packetDialogTitle += '-请求参数'
        }
        // 缓存
        let pData = this.packetPostData
        let pDataCache = this.packetPostDataCache
        pDataCache.fieldCode = pData.fieldCode || ''
        pDataCache.fieldType = pData.fieldType || ''
        pDataCache.fieldRequired = pData.fieldRequired || ''
        pDataCache.fieldLength = pData.fieldLength || ''
        pDataCache.fieldName = pData.fieldName || ''
        pDataCache.fieldDefVal = pData.fieldDefVal || ''
        pDataCache.fieldEncoding = pData.fieldEncoding || ''
        pDataCache.fieldPattern = pData.fieldPattern || ''
        // 缓存结束
        this.iType = type
        this.packetDialogVisible = true
      },
      packetDialogSubmit () {
        // 校验
        this.$refs['packetPostForm'].validate((valid) => {
          if (valid) {
            // 编码方式默认utf-8
            if (!this.packetPostData.fieldEncoding) {
              this.packetPostData.fieldEncoding = 'UTF-8'
            }
            if (!this.packetPostData.fieldRequired) {
              this.packetPostData.fieldRequired = false
            }
            if (!this.packetPostData.fieldDefVal) {
              this.packetPostData.fieldDefVal = ''
            }
            if (!this.packetPostData.fieldPattern) {
              this.packetPostData.fieldPattern = ''
            }
            if (this.iPacket) {
              if (this.iType === 'res') {
                this.packetData.resPacketList.push(this.packetPostData)
              } else if (this.iType === 'req') {
                this.packetData.reqPacketList.push(this.packetPostData)
              }
            }
            this.packetData.moduleId = this.Data.moduleId
            var that = this
            Object.keys(this.packetPostData).forEach(function (key) {
              that.rowCache[key] = that.packetPostData[key]
            })
            // 执行ajax，送packetData
            ajax.post(api.SETMODULELINKPACKET, this.packetData, true).then(res => {
              if (res === 'success') {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.packetDialogVisible = false
                this.getPacketList()
              }
            }).catch(res => {
              this.$message({
                showClose: true,
                message: res.errorMsg,
                type: 'warning'
              })
              this.getPacketList()
            })
          } else {
            return false
          }
        })
      },
      packetDialogReset () {
        this.$refs['packetPostForm'].resetFields()
          if (this.iPacket) {
          this.packetPostData = {}
          } else {
            let pData = this.packetPostData
            let pDataCache = this.packetPostDataCache
            pData.fieldCode = pDataCache.fieldCode
            pData.fieldType = pDataCache.fieldType
            pData.fieldRequired = pDataCache.fieldRequired
            pData.fieldLength = pDataCache.fieldLength
            pData.fieldName = pDataCache.fieldName
            pData.fieldDefVal = pDataCache.fieldDefVal
            pData.fieldEncoding = pDataCache.fieldEncoding
            pData.fieldPattern = pDataCache.fieldPattern
          }
      },
      packetDialogClose () {
        this.packetDialogVisible = false
        // if (!this.iPacket) {
          this.packetPostDataCache = {}
        // this.getPacketList()
        // }
        this.iPacket = null
        this.iType = ''
        // this.$refs['packetPostForm'].resetFields()
      },
      removePacket (fieldId, linkId) {
        this.$confirm('确定要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ajax.post(api.REMOVEPACKET, {fieldId: fieldId, linkId: linkId}, true).then(res => {
            if (res === 'success') {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getPacketList()
            }
          }).catch(res => {
            this.$message({
              showClose: true,
              message: res.errorMsg,
              type: 'warning'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      getRuleList (e = 1, s = 10) {
        ajax.post(api.LISTAPIRULE + '?pageNum=' + e + '&pageSize=' + s, {}, true).then(res => {
          this.ruleData = res
        }).catch(res => {
          this.$message({
            showClose: true,
            message: res.errorMsg,
            type: 'warning'
          })
        })
      },
      getPacketList () {
        ajax.post(api.LISTMODULELINKPACKET, {moduleId: this.Data.moduleId}, true).then(res => {
          this.packetData = res
        }).catch(res => {
          this.$message({
            showClose: true,
            message: res.errorMsg,
            type: 'warning'
          })
        })
        this.getRuleList()
      },
      // 关闭选择模块列表弹窗
      closeDialog () {
        this.ruleDialogVisible = false
      },
      // 处理模块列表分页
      handlePageChanges (params) {
        this.handleCurrentChange(params.currentPage)
      }
    },
    mounted () {
      this.getPacketList()
    }
  }
</script>
<style lang="stylus" rel="stylesheet/stylus">
  #set-field-data
    .bg-color-w
      background-color white
    .mar-t-10
      margin-top 10px
    .form-title
      padding 10px
      .form-title-btn
        float right
    .select
      display block
      width 100%
      padding 0 15px
      height 40px
      line-height 40px
      border 1px solid #dcdfe6
      border-radius 4px
      background #f5f5f5
      box-sizing border-box
</style>
